<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/5
 * Time: 19:29
 */

namespace app\index\logic;

use app\common\utils\WeChatUtils;
use think\Config;
use think\Exception;
use think\Log;

class MessageLogic
{
    /**
     * 发送文本消息
     * @param $user_id
     * @param $message
     */
    public function sendMessage($user_id,$message){
        try {
            $this->send($message,$user_id);
        }catch (Exception $exception){
            Log::write('sendMessage'.$exception->getMessage());
        }
    }


    public function sendMessageText($user_id,$message){
        try {
            $this->send($message,$user_id);
        }catch (Exception $exception){
            Log::write('sendMessage'.$exception->getMessage());
        }
    }

    private function send($message,$user_id){
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        $open_id = model('User')->where(array('id' => $user_id))->value('open_id');
        if ($open_id && !empty($open_id)) {
            $msgArray = array(
                "touser" => $open_id,
                "msgtype" => "text",
                "text" => array(
                    "content" => urlencode($message)
                )
            );
            $json = urldecode(json_encode($msgArray));
//            var_dump($json);
            $ch = curl_init();
            $token = $utils->getAccessToken();
            curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $token);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $res = curl_exec($ch);
            curl_close($ch);
        }
    }

//    public function sendRedEnvelopeMessage($user_id,$message_type,$red_envelope_id){
//        try {
//            $message = model('Config')->where(array('name' => $message_type))->value('value');
//            $html = "<a href='http://redpacket.duodukeji.com/pages/answer.html?id=$red_envelope_id'>点击查看挑战详情</a>";
//            $this->send($message.$html,$user_id);
//        }catch (Exception $exception){
//            Log::write('sendRedEnvelopeMessage'.$exception->getMessage());
//        }
//    }
}